package com.ruizhong.PIW.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruizhong.PIW.dao.TTableColumnMapper;
import com.ruizhong.PIW.entity.TColumn;
import com.ruizhong.PIW.entity.TTableColumn;
import com.ruizhong.PIW.service.ColumnService;
import com.ruizhong.PIW.service.TableColumnService;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class TableColumnServiceImpl extends ServiceImpl<TTableColumnMapper, TTableColumn> implements TableColumnService {
    @Autowired
    private ColumnService columnService;

    @Override
    public List<TColumn> getColumn(Integer tableId) {
        if (tableId==null) {
            throw new RuntimeException("请求参数不合法");
        }
        List<TTableColumn> tableColumns = lambdaQuery()
                .select(TTableColumn::getColumnId,TTableColumn::getWidth)
                .eq(TTableColumn::getTableId, tableId)
                .orderBy(Boolean.TRUE,Boolean.TRUE,TTableColumn::getOrdered)
                .list();
        Map<Integer, Integer> idWidthMap = tableColumns.stream().collect(Collectors.toMap(TTableColumn::getColumnId, tTableColumn -> {
            return tTableColumn.getWidth() == null?-1:tTableColumn.getWidth();
        }));
        if (CollectionUtils.isEmpty(tableColumns)) {
            return Collections.EMPTY_LIST;
        }
        List<Integer> columnIds = tableColumns.stream().map(TTableColumn::getColumnId).collect(Collectors.toList());
//        String idsOrdered = columnIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        List<TColumn> list = columnService.lambdaQuery()
                .in(TColumn::getId, columnIds)
//                .last("order by FIELD(id,"+ idsOrdered +")")
                .list();
        for (TColumn tColumn : list) {
            tColumn.setWidth(idWidthMap.get(tColumn.getId()));
        }
        return list;
    }


}
